import React, { Fragment } from 'react'
import { StyleSheet, Animated, Easing, LayoutAnimation, View, FlatList, RefreshControl, Text } from 'react-native'
import BasePage from 'src/pageP/base/base-page/index'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import { blackPost, cancelCollectionPost, collectionPost, homeFamousList } from 'src/utils/RequestAPI'
import { ScaleS, STATUSBAR_HEIGHT, WIDTH } from 'src/utils/ScreenUtil'
import { ONE_PIXEL, ScaleT } from '../../../utils/ScreenUtil'
import { education } from 'src/utils/ConfigUtil'
import { getAreaListByCityName, getIndustryCategory } from '../../../utils/RequestAPI'
import EmptyView from '../../../components/empty-view/index'
import { iosAppFilter } from '../../../utils/ConfigUtil'
import { FamousSwiperHeight } from './components/FamousSwiper'
import { DismissLoading, ShowLoading } from 'src/utils/ToastUtil'
import HeaderComponent from 'src/pageP/home/home-page/components/HeaderComponent'
import { TabView } from 'react-native-tab-view'
import CustomFlatList from 'src/components/custom-flat-list'
import { showModal, showTipModal } from 'src/utils/ModalUtil'
import WhiteWrap from 'src/pageP/home/home-page/components/WhiteWrap'
import ThreeDotComponent from 'src/pageP/home/home-page/components/ThreeDotComponent'
import NavigationUtil from 'src/utils/NavigationUtil'
import { getScale, getTranslateX } from 'src/utils/TabViewUtil'

const filterViewMaxH = ScaleS(400)
const searchHeight = STATUSBAR_HEIGHT + ScaleS(20) + ScaleS(42)
const bannerHeight = (WIDTH - ScaleS(40)) * 150 / 335 + 26 + ScaleS(15)
const topViewHeight = ScaleS(31) + ScaleS(46) + ScaleS(52) + ONE_PIXEL
const SUCCESS = 'success'
const ERROR = 'error'

const routes = [
  { key: 'partTime', title: '兼职' },
  { key: 'practice', title: '实习' },
  { key: 'fullTime', title: '全职' }
]

const dataKeys = [
  'partTimeDataArr',
  'practiceDataArr',
  'fullTimeDataArr'
]

class BaseHomePage extends BasePage {
  constructor (props) {
    super(props)
    this.FamousSwiperHeightAdded = false
    const { landmark: { cityName } } = props
    this.state = {
      famous: null,

      filterArr: this._initFilterArr(),
      index: 0,
      routes: routes,
      partTimeDataArr: [],
      practiceDataArr: [],
      fullTimeDataArr: [],
      withPostCategory: [[], [], []]
    }
    this.dataKeys = dataKeys
    this.flatList = [
      {
        flatListRef: null,
        filterArr: this._initFilterArr(),
        cityName: cityName,
        industries: []
      },
      {
        flatListRef: null,
        filterArr: this._initFilterArr(),
        cityName: cityName,
        industries: []
      },
      {
        flatListRef: null,
        filterArr: this._initFilterArr(),
        cityName: cityName,
        industries: []
      }
    ]
    this.currentIndex = 0
    this.renderItem = this.renderItem.bind(this)
    this.postFunc = this.postFunc.bind(this)
    this.snapshotBeforeUpdate = this.snapshotBeforeUpdate.bind(this)
    this.changeRefresh = this.changeRefresh.bind(this)
    this.educationArr = this._getEducationArr()
    this.areaArr = []
  }

  _initFilterArr = () => {
    const { landmark: { cityName } } = this.props
    return [
      {
        label: '推荐',
        isActive: false
      },
      {
        label: '筛选职位',
        isActive: false
      },
      {
        // label: cityName,
        label: '区域',
        isActive: false
      },
      {
        label: '学历',
        isActive: false
      }
    ]
  }

  _getEducationArr = () => {
    const educationContent = education.reduce((totalValue, currentItem) => {
      const item = {
        label: currentItem.key,
        value: currentItem.educationValue,
        type: 'education'
      }
      totalValue.push(item)
      return totalValue
    }, [{
      label: '全部',
      type: 'education',
      isAll: true
    }])

    return [{
      title: null,
      content: educationContent
    }]
  }

  componentDidMount () {
    this._initIndustryCategory()
    this._onRequestRefresh(true)
    this._getAreaListByCityName()
    this._homeFamousList()
  }

  getSnapshotBeforeUpdate (prevProps, prevState) {
    console.log('getSnapshotBeforeUpdate', prevProps, this.props)
    if (prevProps.landmark.cityName !== this.props.landmark.cityName) { // props城市改变
      console.info('this.props.landmark.cityName', prevProps.landmark.cityName, this.props.landmark.cityName)
      this.cityChanged(this.props.landmark.cityName)
    }
    this.snapshotBeforeUpdate(prevProps, prevState)
    return null
  }

  /**
   * 城市改变
   * @param cityName
   */
  cityChanged = cityName => {
    const resetFilterArr = () => {
      this.flatList.forEach((item) => {
        item.filterArr[2].label = cityName
      })
      this.homeListParams.forEach((item, index) => {
        this._deleteHomeListParams(this.areaKey, index)
      })
      this.setState({
        filterArr: [...this.flatList[this.currentIndex].filterArr]
      })
    }
    setImmediate(() => {
      if (this.flatList[this.currentIndex].cityName !== cityName) {
        this.flatList[this.currentIndex].cityName = cityName
        resetFilterArr()
        this._getAreaListByCityName()
        this._homeFamousList()
        this._onRequestRefresh(true)
      }
    })
  }

  snapshotBeforeUpdate (prevProps, prevState) {
  }

  _initIndustryCategory = () => {
    (async () => {
      await this._getIndustryCategory(0, 0)
      await this._getIndustryCategory(2, 1)
      await this._getIndustryCategory(1, 2)
    })().then()
  }

  _getIndustryCategory = (type, index) => {
    getIndustryCategory({ params: { type } }).then((data) => {
      const industries = this._getIndustries(data.data)
      this.flatList[index].industries = industries
    })
  }

  _getIndustries = (industries) => {
    return industries.reduce((totalValue, currentItem) => {
      const item = {
        title: currentItem.name,
        content: currentItem.industryCategories.map((innerItem) => {
          return {
            label: innerItem.name,
            type: this.categoryKey,
            value: [currentItem.name, innerItem.name]
          }
        })
      }
      totalValue.push(item)
      return totalValue
    }, [{
      title: '全部',
      content: [{ label: '全部', type: this.categoryKey, isAll: true }]
    }])
  }

  _getAreaListByCityName = () => {
    const { landmark: { cityName } = {} } = this.props
    const getAreaArr = (areas) => {
      const { landmark: { cityName } = {} } = this.props
      const areaContent = areas.reduce((totalValue, item) => {
        totalValue.push({
          label: item,
          value: this._isPageB() ? [item] : item,
          type: this.areaKey
        })
        return totalValue
      }, [{
        label: '全' + cityName,
        type: this.areaKey,
        isAll: true
      }])
      return [
        {
          title: null,
          content: areaContent
        }
      ]
    }
    getAreaListByCityName({
      params: {
        cityName
      }
    }).then((data) => {
      this.areaArr = getAreaArr(data.data)
    })
  }

  _isPageB = () => {
    return this.pageType === 'B'
  }

  /**
   * 首页名企加载
   * @private
   */
  _homeFamousList = () => {
    if (!this._isPageB()) {
      const { landmark: { cityName: city } = {} } = this.props
      homeFamousList({ params: { city } }).then((data) => {
        console.info(data)
        const { data: famous = [] } = data
        LayoutAnimation.easeInEaseOut()
        if (famous.length > 0) {
          // TODO
          if (!this.FamousSwiperHeightAdded) {
            this.moveAbleHeight = this.moveAbleHeight + FamousSwiperHeight
            this.FamousSwiperHeightAdded = true
          }
          this.setState({
            famous: famous.map((e, index) => ({ ...e, index }))
          })
        } else {
          if (this.FamousSwiperHeightAdded) {
            this.moveAbleHeight = this.moveAbleHeight - FamousSwiperHeight
            this.FamousSwiperHeightAdded = false
          }
          this.setState({
            famous: null
          })
        }
      })
    }
  }

  childRender () {
    return (
      <View style={styles.container}>
        <TabView
          style={styles.tabView}
          navigationState={this.state}
          renderScene={this._renderScene}
          onIndexChange={this._onIndexChange}
          renderTabBar={this._renderTabBar}
        />
      </View>
    )
  }

  _renderTabBar = (props) => {
    const { landmark, role } = this.props
    const { filterArr, withPostCategory } = this.state
    return (
      <HeaderComponent
        {...props}
        role={role}
        landmark={landmark}
        orderLabel={this.orderLabel}
        borderTagClick={this._borderTagClick}
        filterArr={filterArr}
        regionArr={this.areaArr}
        educationArr={this.educationArr}
        positionArr={this.flatList[this.currentIndex].industries}
        withPostCategory={withPostCategory}
      />
    )
  }

  /**
   * 切换标签
   * @param index
   * @private
   */
  _onIndexChange = (index) => {
    this.currentIndex = index
    const { landmark: { cityName } } = this.props
    console.info('this.flatList', this.flatList)
    this.setState({
      index,
      filterArr: [...this.flatList[index].filterArr]
    }, () => {
      if (this.state[dataKeys[index]].length <= 0) {
        if (this._isPageB()) {
          const { BMineCenterStore: { haveCompanyApply: { companyId: thisCompanyId } } } = this.props
          if (thisCompanyId) {
            this.initRequestRefresh(thisCompanyId)
          } else {
            this._onRequestRefresh()
          }
        } else {
          this._onRequestRefresh()
        }
      } else if (this.flatList[index].cityName !== cityName) {
        this._onRequestRefresh()
      } else {
        if (this._isPageB()) { // B端
          this.changeRefresh(
            // {
            //   postSameCallBack: this._setDataFromCache,
            //   notPostCallBack: this._setDataFromCache,
            //   noCompanyIdCallBack: this._setDataFromCache
            // }
          )
        }
      }
    })
  }

  changeRefresh () {
  }

  /**
   * 渲染每一个屏
   * @param route
   * @param jumpTo
   * @returns {*}
   * @private
   */
  _renderScene = (params) => {
    const { route } = params
    const { partTimeDataArr, practiceDataArr, fullTimeDataArr } = this.state
    switch (route.key) {
      case routes[0].key:
        return this._renderPageComponent(0, partTimeDataArr)
      case routes[1].key:
        return this._renderPageComponent(1, practiceDataArr)
      case routes[2].key:
        return this._renderPageComponent(2, fullTimeDataArr)
    }
  }

  _renderPageComponent = (index, data) => {
    return (
      <CustomFlatList
        ref={this._flatListRef}
        index={index}
        style={styles.flatList}
        renderItem={this.renderItem}
        data={data}
        keyExtractor={this._keyExtractor}
        onHeaderRefresh={this._onHeaderRefresh}
        onFooterRefresh={this._onFooterRefresh}
        ListEmptyComponent={this._listEmptyComponent()}
        showsVerticalScrollIndicator={false}
      />
    )
  }

  _scrollToTopRefresh = (animated = true) => {
    if (this.flatList[this.currentIndex] && this.flatList[this.currentIndex].flatListRef) {
      this.flatList[this.currentIndex].flatListRef.scrollToTop(animated)
      this.flatList[this.currentIndex].flatListRef.beginHeaderRefresh(RefreshState.Idle)
    }
  }

  _flatListRef = (ref) => {
    if (ref && ref.props) {
      const { index } = ref.props
      this.flatList[index].flatListRef = ref
    }
  }

  _listEmptyComponent = () => {
    return (
      <EmptyView emptyImg={require('src/imgC/home/post_no_data.png')} style={styles.emptyView} firstTip={'...'}/>
    )
  }

  /**
   * 标记的筛选
   * @param isActive
   * @param params
   * @private
   */
  _borderTagClick = (isActive, params, index) => {
    this._configRequestHeader(isActive, params)
    this._setFilterText(params, index)
    this._onRequestRefresh()
  }

  _setFilterText = (params, index) => {
    const { filterArr } = this.state
    const newFilterArr = filterArr.map((item, i) => {
      if (index === i) {
        item.label = params.firstLabel || params.label
        item.fullLabel = params.label
      }
      return item
    })
    this.flatList[this.currentIndex].filterArr = newFilterArr.map((item) => {
      const newItem = { ...item, label: item.label, isActive: false }
      return newItem
    })
    this.setState({ filterArr: newFilterArr })
  }

  /**
   * 配置请求头
   * @private
   */
  _configRequestHeader = (isActive, params) => {
    if (isActive) {
      if (params.isAll) {
        this._deleteHomeListParams(params.type)
      } else {
        this._addHomeListParams(params.type, params.value)
      }
    }
  }

  /**
   * 添加请求参数
   * @param key
   * @param value
   * @private
   */
  _addHomeListParams = (key, value) => {
    this.homeListParams[this.currentIndex][key] = value
  }

  /**
   * 删除请求参数
   * @param key
   * @private
   */
  _deleteHomeListParams = (key, index = this.currentIndex) => {
    const item = this.homeListParams[index]
    if (key in item) delete item[key]
  }

  _keyExtractor = (item) => {
    return item.id.toString()
  }

  /**
   * 渲染每一条
   */
  renderItem () {

  }

  /**
   * 下来刷新
   * @private
   */
  _onHeaderRefresh = (showLoading) => {
    // this._resetFilterCondition()
    this._onRequestRefresh(showLoading)
  }

  /**
   * 重置刷选条件
   * @private
   */
  _resetFilterCondition = () => {
    this._deleteHomeListParams(this.categoryKey)
    this._deleteHomeListParams(this.orderKey)
    this._deleteHomeListParams(this.areaKey)
    this._deleteHomeListParams('education')
  }

  /**
   * 请求刷新
   * @private
   */
  _onRequestRefresh = (showLoading) => {
    showLoading && ShowLoading()
    this.homeListParams[this.currentIndex][this.pageKey] = 1
    this._homePostList().then((data) => {
      // showLoading && DismissLoading()
      DismissLoading()
      if (data.status === SUCCESS) {
        this._setDataState(iosAppFilter(data.data, ['basicInfoModel', 'name']), () => {
          this._setEndRefreshingState(data.data)
        })
      } else {
        this._setEndRefreshState(RefreshState.Failure)
      }
    })
  }

  /**
   * 上拉加载
   * @private
   */
  _onFooterRefresh = () => {
    const currentPage = this.currentIndex
    this.homeListParams[currentPage][this.pageKey]++
    const dataArr = this.state[dataKeys[this.currentIndex]]
    this._homePostList().then((data) => {
      if (data.status === SUCCESS) {
        this._setDataState(dataArr.concat(iosAppFilter(data.data, ['basicInfoModel', 'name'])), () => {
          this._setEndRefreshingState(data.data)
        })
      } else {
        this.homeListParams[currentPage][this.pageKey]--
        this._setEndRefreshState(RefreshState.Failure)
      }
    })
  }

  /**
   * 请求数据
   * @returns {Promise}
   * @private
   */
  _homePostList = () => {
    const { landmark, userId } = this.props
    return new Promise((resolve) => {
      return this.postFunc()({
        params: {
          ...this.homeListParams[this.currentIndex],
          [this.cityNameKey]: landmark.cityName,
          userId
        }
      }).then((data) => {
        resolve({
          status: SUCCESS,
          data: data.data
        })
      }).catch(() => {
        resolve({
          status: ERROR
        })
      })
    })
  }

  /**
   * 请求的接口必传
   */
  postFunc () {
  }

  _setDataState = (value, callback) => {
    this.setState({
      [dataKeys[this.currentIndex]]: value
    }, callback)
  }

  _setEndRefreshingState = (data) => {
    if (data && data.length > 9) {
      this._setEndRefreshState(RefreshState.CanLoadMore)
    } else {
      this._setEndRefreshState(RefreshState.NoMoreData)
    }
  }

  _setEndRefreshState = (state) => {
    this.flatList[this.currentIndex].flatListRef.endRefreshing(state)
  }

  /**
   * 点击三个点的回调
   */
  threeDotPress = (item) => {
    this.showDotModal = showModal(this._threeDotModal(item))
  }

  _threeDotModal = (params) => {
    return (
      <WhiteWrap>
        <ThreeDotComponent dataArr={this.dotArr} params={params} itemClick={this._itemDotClick}/>
      </WhiteWrap>
    )
  }

  _itemDotClick = ({ item, params }) => {
    this.showDotModal.close(() => {
      console.info('showDotModal', item, params)
      const { type } = item
      const { id: jobDetailId } = params
      switch (type) {
        case 0:// 举报
          NavigationUtil.navigateWithLogin({
            routeName: 'CompanyReport',
            navigateParams: {
              jobDetailId
            }
          })
          break
        case 1:// 关注，收藏
          this._collection(params)
          break
        case 2:// 取消关注，收藏
          this._unCollection(item.collectionId)
          break
        case 3:// 不感兴趣，屏蔽
          this._onBlockClick(jobDetailId)
          break
      }
    })
  }

  _collection = (params) => {
    if (NavigationUtil.jumpLogin()) {
      return
    }
    this.collection(params).then(() => {
    })
  }

  _unCollection = (collectionId) => {
    if (NavigationUtil.jumpLogin()) {
      return
    }
    this.unCollection(collectionId).then(() => {
    })
  }

  /**
   * 收藏
   */
  collection (params) {
    return new Promise((resolve) => {
      resolve()
    })
  }

  /**
   * 取消收藏
   */
  unCollection (collectionId) {
    return new Promise((resolve) => {
      resolve()
    })
  }

  /**
   * 屏蔽
   * @private
   */
  _onBlockClick = (postId) => {
    if (NavigationUtil.jumpLogin()) {
      return
    }
    const onConfirm = () => {
      blackPost({ params: { postId } }).then(() => {
        const dataArr = this.state[dataKeys[this.currentIndex]]
        const newDataArr = dataArr.filter((item) => {
          return item.id !== postId
        })
        this.setState({ [dataKeys[this.currentIndex]]: newDataArr })
        // 屏蔽成功
        this.tipPrompModal.close(() => {
          this.tipPrompModal = null
        })
      })
    }
    this.tipPrompModal = showTipModal({
      titleText: '屏蔽提示',
      contentText: '是否要屏蔽该岗位？屏蔽后该岗位将不再显示',
      confirmText: '确定',
      onCancel: () => {
        this.tipPrompModal.close()
      },
      onConfirm
    })
  }
}

export default BaseHomePage

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  tabView: {
    flex: 1
  },
  flatList: {
    flex: 1
  },
  headerContainer: {
    width: '100%',
    height: 100,
    justifyContent: 'center'
  },
  text: {
    color: '#fff',
    fontSize: 30,
    fontWeight: 'bold'
  },
  scrollableTabView: {
    flex: 1
  },
  containerStyle: {
    // minHeight: HEIGHT + moveAbleHeight
  },
  emptyView: {
    flex: 1
  },
  tabHeaderView: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    backgroundColor: 'white'
  },
  tabSearchBtn: {
    marginTop: ScaleS(36),
    marginRight: ScaleS(20)
  },
  tabSearchImg: {
    width: ScaleS(25),
    height: ScaleS(25)
  },
  filterView: {
    flexDirection: 'row',
    paddingHorizontal: ScaleS(20),
    height: ScaleS(52),
    alignItems: 'center',
    backgroundColor: 'white',
    justifyContent: 'space-between',
    borderBottomColor: 'rgba(120,120,120,0.2)',
    borderStyle: 'solid',
    borderBottomWidth: ONE_PIXEL
  },
  filterItemView: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  filterText: {
    color: '#999999',
    fontSize: ScaleT(16),
    fontWeight: '500',
    marginRight: ScaleS(10)
  },
  filterActiveText: {
    color: '#444444'
  },
  filterImage: {
    width: ScaleS(5),
    height: ScaleS(4)
  },
  filterPositionView: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    zIndex: 2
  },
  filterNullView: {
    width: '100%',
    height: topViewHeight
  },
  filterBgOutView: {
    position: 'absolute',
    top: topViewHeight,
    width: '100%',
    height: '100%',
    backgroundColor: 'transparent'
  },
  filterBgView: {
    width: '100%',
    height: '100%',
    backgroundColor: 'rgba(0,0,0,0.7)'
  },
  filterContentView: {
    position: 'absolute',
    top: 0,
    width: '100%',
    zIndex: 3,
    borderBottomRightRadius: ScaleS(10),
    borderBottomLeftRadius: ScaleS(10),
    overflow: 'hidden',
    borderTopColor: '#F7F7F7',
    borderStyle: 'solid',
    borderTopWidth: ONE_PIXEL,
    paddingHorizontal: ScaleS(20),
    backgroundColor: 'white'
  },
  contentContainer: {
    paddingBottom: ScaleS(23)
  },
  orderView: {},
  orderItemView: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: ScaleS(28),
    borderBottomColor: 'rgba(120,120,120,0.2)',
    borderStyle: 'solid',
    borderBottomWidth: ONE_PIXEL
  },
  orderItemText: {
    color: '#444444',
    fontSize: ScaleT(16),
    fontWeight: '400'
  },
  orderItemTextActive: {
    color: '#FFC61C'
  },
  orderItemImg: {
    width: ScaleS(15),
    height: ScaleS(10)
  },
  educationView: {
    paddingVertical: ScaleS(26)
  },
  educationTitle: {
    color: '#444444',
    fontSize: ScaleT(16),
    fontWeight: '500'
  },
  educationContentView: {
    flexDirection: 'row',
    flexWrap: 'wrap'
  },
  tagView: {
    marginLeft: ScaleS(16),
    marginTop: ScaleS(24)
  },
  tagText: {
    color: '#666666',
    fontSize: ScaleT(14),
    fontWeight: '400'
  }
})
// https://github.com/Micjoyce/ScrollViewWithTabView
